<template>
  <div class="FireDialog">
    <el-dialog title="火化信息维护" :visible.sync="$parent.DialogFire" width="80%" v-dialogDrag @close="closeDialog()">
      <el-form :model="copyFireInfo.cremation" :rules="rules" :inline="true" label-width="110px" ref="Fire">
        <el-row :gutter="5">
          <!-- <el-form-item label="火化类型:">
             <el-select v-model="copyFireInfo.cremation.cremationTypeCode"  @change="checkDeadUser" placeholder="请选择">
               <el-option
                 v-for="(item,index) in cremationTypes"
                 :key="index"
                 :label="item.dataText"
                 :value="item.dataCode"
                 :disabled="item.disableState>0?true:false"/>
             </el-select>
           </el-form-item>-->
          <el-form-item label="火化炉类型:" prop="furnaceTypeCode">
            <el-select v-model="copyFireInfo.cremation.furnaceTypeCode"
                       onkeydown="return (event.keyCode!=8)"
                       :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false"
                       @change="changeTypeCodeAsRuleItem(copyFireInfo.cremation.furnaceTypeCode)" placeholder="请选择">
              <el-option
                v-for="(item,index) in ruleItemsMini"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="火化计费类型:">
            <el-select v-model="copyFireInfo.cremation.cremationChargeTypeCode"
                       :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false"
                       @change="changeTypeCodeAsRuleItem(copyFireInfo.cremation.furnaceTypeCode)" placeholder="请选择">
              <el-option
                v-for="(item,index) in cremationChargeTypes"
                :key="index"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>

        </el-row>
        <el-row :gutter="5">
          <el-form-item label="是否预约:" prop="asAppointment">
            <el-select v-model="copyFireInfo.cremation.asAppointment"
                       :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false"
                       filterable placeholder="请选择" class="w150">
              <el-option :key="item.dataCode"
                v-for="item in yesorno"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>

          <el-form-item label="火化日期:" prop="appointmentDate">
            <el-date-picker v-if="copyFireInfo.cremation.asAppointment==0"
                            v-model="copyFireInfo.cremation.appointmentDate" :picker-options="pickerOptions0"
                            type="date"
                            :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false"
                            placeholder="选择日期" style="width: 100%;">
            </el-date-picker>
            <el-input v-else-if="copyFireInfo.cremation.asAppointment==1" v-model="selectShow.showtime"
                      :disabled="true">
              <span slot="append" style="cursor: pointer;" @click="showDialog">选择</span>
            </el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="骨灰处理方式:">
            <el-select v-model="copyFireInfo.cremation.ashHandleTypeCode"
                       :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false"
                       onkeydown="return (event.keyCode!=8)"
                       placeholder="请选择" style="width: 120px;">
              <el-option
                v-for="item in ashHandleTypes"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="骨灰去向:">
            <el-select v-model="copyFireInfo.cremation.ashWhereaboutsCode"
                       :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false"
                       placeholder="请选择" style="width: 120px;">
              <el-option
                v-for="item in ashWhereabouts"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState>0?true:false"/>
            </el-select>
          </el-form-item>

          <el-form-item label="火化费用：">
            <el-input v-model="copyFireInfo.cremation.charges.businessCharge.itemCharge"
                      type="number" :readonly="true"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="规则描述：">
            <el-input type="textarea" v-model="copyFireInfo.cremation.ruleRemark" :readonly="true"
                      style="width: 610px;"></el-input>
          </el-form-item>

        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注：">
            <el-input type="textarea" v-model="copyFireInfo.cremation.remark" :disabled="copyFireInfo.cremation.charges.businessCharge.asSettled>0?true:false" style="width: 610px;"></el-input>
          </el-form-item>
        </el-row>
        <div class="tablewrapper">
          <div class="table">
            <div class="title"><span>所有物品、服务</span>
            </div>
            <el-table
              :data="copyGoodServices"
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              border
              style="width: 99%;">
              <el-table-column align='center' prop="itemName" label="收费项目" sortable min-width="120"
                               column-key="serviceItemId">
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                min-width="80">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" v-if="row.asFixPrice !=1"
                         type="number" onkeyup="value=(value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                         v-model="row.itemPrice">
                  <label class="edit-cell" v-if="row.asFixPrice ==1">{{ row.itemPrice }}</label>
                </template>
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                min-width="50">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" v-model="row.itemNumber"
                         type="number" onkeyup="value=(value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                  >
                </template>
              </el-table-column>

              <el-table-column
                prop="itemUnit"
                align='center'
                label="单位"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="总金额"
                min-width="80">
                <template slot-scope="{row,$index}"
                          v-if="Number(row.itemPrice)>=0 &&Number(row.itemNumber)>=0&&Number(row.discountCharge)>=0">
                  {{
                    Number((row.itemPrice.match(/^\d+(?:.\d{0,2})?/)) * (row.itemNumber.match(/^\d+(?:.\d{0,2})?/))).toFixed(2)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                min-width="50">
                <template slot-scope="{row,$index}">
                  <input class="edit-cell" v-model="row.discountCharge"
                         onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null">
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="itemSurplusNum"
                label="物品剩余">
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'
                width="100">
                <template slot-scope="{row,$index}">
                  <el-button
                    @click.native.prevent="AddRow($index,copyGoodServices)"
                    type="text"
                    size="small">
                    追加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--<p class="tablecont">单价、数量、优惠三个字段值允许工作人员直接更改，更改完成后可通过“追加”按钮进行费用追加。</p>-->
          </div>
          <div class="table">
            <h3 class="title">已追加物品、服务</h3>
            <el-table
              :data="copyFireInfo.cremation.charges.goodsServices"
              :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
              border
              style="width: 99%;">
              <el-table-column align='center' prop="itemName" label="收费项目" min-width="100">
              </el-table-column>
              <el-table-column
                prop="itemPrice"
                align='right'
                label="单价"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="itemNumber"
                align='right'
                label="数量"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemUnit"
                align='center'
                label="单位"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="itemCharge"
                align='right'
                label="项目金额"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="discountCharge"
                align='right'
                label="优惠"
                min-width="80">
              </el-table-column>
              <el-table-column
                prop="benefitCharge"
                align='right'
                label="减免"
                min-width="50">
              </el-table-column>
              <el-table-column
                prop="asSettled"
                align='center'
                label="结算状态"
                width="80">
                <template slot-scope="{row,$index}">
                  <span v-if="row.asSettled==0">未结算</span>
                  <span v-else-if="row.asSettled==1">已结算</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align='center'
                width="80">
                <template slot-scope="{row,$index}">
                  <el-button v-if="row.asSettled==0"
                             @click.native.prevent="deleteRow($index,copyFireInfo.cremation.charges.goodsServices)"
                             type="text"
                             size="small">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--<p class="tablecont">此区域费用信息不允许更改，仅未结算的费用可以进行删除操作。-->
            <!--无论是新追加的费用还是删除的费用，均在保存操作后生效。-->
            <!--</p>-->
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" @click="Save()" :disabled="saveFlag">保 存</el-button>
        <el-button type="primary" plain @click="$parent.DialogFire = false">取 消</el-button>
      </div>
      <el-dialog
        title="选择时间段"
        :visible.sync="centerDialogVisible" width="80%"
        class="selecttime"
        center>
        <el-row :gutter="5">
          <label style="line-height: 40px;">当前选中时间:
            <el-date-picker v-if="searchDate"
                            v-model="searchDate"
                            type="date"
                            placeholder="选择日期" readonly>
            </el-date-picker>
            -
            <el-input v-model="selectClick.appointmentTimeSegment"></el-input>
          </label>
        </el-row>
        <el-row :gutter="5" style="display: flex;">
          <el-calendar v-model="searchDate" style="width:400px;">
          </el-calendar>
          <div class="wrapper">
            <div class="box-card" v-if="timeList.length>0" v-for="(n,m) in timeList" :key="m">
              <div class="item"
                   :class="{free:n.appointmentCount==0?true:false,employ:n.appointmentCount==1?true:false,selected:n.flag}"
                   @click.stop="timeSelect(m)">
                <h2>{{ n.appointmentTimeSegment }}</h2>
              </div>
            </div>
          </div>
        </el-row>
        <span slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" @click="showSelectName()">确 定</el-button>
        <el-button type="primary" plain @click="centerDialogVisible = false">取 消</el-button>
      </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import * as Type from '@/api/service'
import {validPhone, isHas} from '@/utils/validate'
import {dataFormate, dataFormatetmd} from '@/utils/index'
import {toFixed} from "@/utils/tofixed"

export default {
  name: "FireDialog",
  props: {
    FireInfo: {
      type: Object,
      default: function () {
        return {
          "cremation": {
            "id": 0,
            "businessCode": "",
            "furnaceTypeCode": "",
            "cremationChargeTypeCode": "",
            "furnaceId": "",
            "asAppointment": "",
            "appointmentDate": "",//预约日期
            "appointmentTimeSegment": "",//预约时间段
            "cremationNo": "",
            "randomCode": "",
            "ashHandleTypeCode": "",
            "ashWhereaboutsCode": "",
            "version": 0,
            "charges": {
              "businessCharge": {
                "id": 0,
                "serviceItemId": 0,
                "itemPrice": 0,
                "itemNumber": 0,
                "itemUnit": "",
                "itemCharge": "",
                "discountCharge": 0,
                "benefitCharge": 0,
                "realityCharge": 0,
                "asSettled": 0,
                "version": 0
              },
              "goodsServices": []
            }
          }
        }
      },
    },
    DialogFire: {
      type: Boolean,
      default: false
    },
    FireAddFlag: {    //true 为新增
      type: Boolean
    }, ruleItems: {
      type: Array
    }, ruleItemsMini: {
      type: Array
    },
    //火化计费类型规则
    ruleChargeItems: {
      type: Array
    },
    //火化
    cremationTypes: {
      type: Array
    },//骨灰处理方式
    ashHandleTypes: {
      type: Array
    },//骨灰去向
    ashWhereabouts: {
      type: Array
    }, //火化计费类型
    cremationChargeTypes: {
      type: Array
    }
  },
  data() {
    return {
      yesorno: [
        {label: '否', value: 0},
        {label: '是', value: 1}],
      dictionary: {},
      copyFireInfo: this.FireInfo,
      copyGoodServices: [],   //已追加服务物品，
      selectShow: {
        showtime: "",
        date: ""
      }, //显示的时间段
      selectClick: {}, //点击的时间段
      timeList: [],//时间段
      searchDate: "",//查询日期
      centerDialogVisible: false,
      rules: {
        furnaceTypeCode: [
          {required: true, message: '请选择火化炉类型', trigger: 'blur'}
        ],
        asAppointment: [
          {required: true, message: '请选择是否预约', trigger: 'blur'}
        ],
        appointmentDate: [
          {required: true, message: '请选择日期', trigger: 'blur'}
        ],
      },
      formLabelWidth: '120px',
      //开始时间小于等于今天可选
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      saveFlag: false,     //保存过程中不可更改,true为正在保存
      //开始时间小于等于今天可选
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      ruleItem: {},//收费规则
      onpresscTime: 0, //  阻止短时间内连续点击
      cremationType: 1//默认遗体
    }
  },
  created() {
    this.$store.dispatch('user/getdictionary').then((res) => {     //获取字典数据
      this.dictionary = res;
      this.$set(this.dictionary, res)
    }).catch(() => console.log('promise catch err'))

  },
  // mounted(){
  //   console.log(435);
  //   this.changeTypeCodeAsRuleItem(this.copyFireInfo.cremation.furnaceTypeCode);
  //   console.log(437);
  // },
  watch: {
    '$parent.DialogFire'() {
      this.copyFireInfo = this.FireInfo
      this.copyGoodServices = JSON.parse(JSON.stringify(this.FireInfo.serviceItems.use_in_cremation))
      if (!this.FireAddFlag) {
        if (this.copyFireInfo.cremation.appointmentDate || this.copyFireInfo.cremation.appointmentTimeSegment) {
          this.selectShow.showtime = this.copyFireInfo.cremation.appointmentDate + " " + this.copyFireInfo.cremation.appointmentTimeSegment
        }
        if (typeof this.copyFireInfo.cremation.appointmentDate == "string" && this.copyFireInfo.cremation.appointmentDate.indexOf("-") > -1) {
          this.copyFireInfo.cremation.appointmentDate = this.copyFireInfo.cremation.appointmentDate.replace(/-/g, "/");
        }
        if (typeof this.copyFireInfo.cremation.appointmentFinishTime == "string" && this.copyFireInfo.cremation.appointmentFinishTime.indexOf("-") > -1) {
          this.copyFireInfo.cremation.appointmentFinishTime = this.copyFireInfo.cremation.appointmentFinishTime.replace(/-/g, "/");
        }
      }

      this.$parent.DialogFire = this.DialogFire
      if (this.$parent.DialogFire == false) {
        this.$nextTick(() => {
          this.$refs.Fire.resetFields();
        })
      }
      this.changeTypeCodeAsRuleItem(this.copyFireInfo.cremation.furnaceTypeCode);
    },
    "searchDate"() {
      this.select(this.searchDate)
    }, "ruleChargeItems"() {
      let str = this.ruleChargeItems;
    }, "ruleItem"() {
      let ruleItemWatch = this.ruleItem;
    }
  },
  methods: {
    //当类型改变时，查找适用计算规则
    changeTypeCodeAsRuleItem(code) {
      console.log(code);
      if (!code) {
        this.$message('code值无效')
        return;
      }
      //console.log(JSON.stringify(this.ruleItems));
      //判断并选择费用
      if (this.ruleItems) {
        for (let i = 0; i < this.ruleItems.length; i++) {
          let item = this.ruleItems[i];
          console.log(this.getPurposeByCode(this.copyFireInfo.cremation.cremationChargeTypeCode));
          //选中code'和用途获得是哪个用途的哪个火化炉型
          if (item.dataCode == code && item.purpose == this.getPurposeByCode(this.copyFireInfo.cremation.cremationChargeTypeCode)) {
            let itemPrice;
            if (null != item.ruleParams) {
              let pObjStr = item.ruleParams;
              let pObj = JSON.parse(pObjStr);
              if (pObj.itemPrice) {
                itemPrice = pObj.itemPrice;
              }
            } else {
              itemPrice = item.itemPrice;
            }
            //服务项目id
            this.copyFireInfo.cremation.charges.businessCharge.serviceItemId = item.serviceItemId;
            //服务项目价格
            this.copyFireInfo.cremation.charges.businessCharge.itemPrice = itemPrice;

            //规则编码
            this.copyFireInfo.cremation.ruleCode = item.ruleCode;
            //规则数量
            this.copyFireInfo.cremation.ruleNumber = item.itemNumber;
            //计量单位
            this.copyFireInfo.cremation.ruleUnit = item.itemUnit;

            //规则描述
            this.copyFireInfo.cremation.ruleRemark = item.ruleDescribe;

            // 计算规则编码
            this.ruleItem.ruleCode = item.ruleCode;
            // 计算规则单价
            this.ruleItem.itemPrice = itemPrice;
            // 计算规则参数
            this.ruleItem.ruleParams = item.ruleParams;


            this.loadChargeWithRule();
            console.log(JSON.stringify(item.ruleParams));
            break;
          }
        }
      }
    },
    //当类型改变时，查找适用计算规则
    changeChargeTypeCodeAsRuleItem(code) {
      if (null == code) {
        this.$message('code值无效')
        return;
      }
      //判断并选择费用
      if (this.ruleChargeItems) {
        for (let i = 0; i < this.ruleChargeItems.length; i++) {
          let item = this.ruleChargeItems[i];
          //选中code'
          if (item.dataCode == code) {
            //服务项目id
            this.copyFireInfo.cremation.charges.businessCharge.serviceItemId = item.serviceItemId;
            //服务项目价格
            this.copyFireInfo.cremation.charges.businessCharge.itemPrice = item.itemPrice;
            //火化费用
            if (item.ruleParams) {
              let ruleParamsObj = JSON.parse(item.ruleParams)
              if (ruleParamsObj.itemPrice) {
                this.copyFireInfo.cremation.charges.businessCharge.itemCharge = ruleParamsObj.itemPrice;
              }
            } else {
              this.copyFireInfo.cremation.charges.businessCharge.itemCharge = item.itemPrice;
            }

            //规则编码
            this.copyFireInfo.cremation.ruleCode = item.ruleCode;
            //规则数量
            this.copyFireInfo.cremation.ruleNumber = item.itemNumber;
            //计量单位
            this.copyFireInfo.cremation.ruleUnit = item.itemUnit;

            //规则描述
            this.copyFireInfo.cremation.ruleRemark = item.ruleDescribe;

            // 计算规则编码
            this.ruleItem.ruleCode = item.ruleCode;
            // 计算规则单价
            this.ruleItem.itemPrice = item.itemPrice;
            // 计算规则参数
            this.ruleItem.ruleParams = item.ruleParams;

            this.$forceUpdate()
            // this.loadChargeWithRule();
            break;
          }
        }
      }
    },
    //计算业务费用调用
    loadChargeWithRule() {
      if (!this.ruleItem) {
        return;
      }


      let ruleData = JSON.parse(this.ruleItem.ruleParams);
      ruleData.itemPrice = this.ruleItem.itemPrice;
      let postData = {
        "ruleCode": this.ruleItem.ruleCode,
        "ruleData": JSON.stringify(ruleData)
      }
      Type['loadChargeWithRule'](postData).then(response => {
        let result = response;
        const {data} = result
        if (!data) {
          this.$message('费用计算信息出错.')
        }

        this.copyFireInfo.cremation.charges.businessCharge.itemCharge = data.itemCharge;
        //规则编码
        this.copyFireInfo.cremation.ruleCode = data.ruleCode;
        //规则数量
        this.copyFireInfo.cremation.ruleNumber = data.ruleNumber;
        //计量单位
        this.copyFireInfo.cremation.ruleUnit = data.ruleUnit;

        //规则描述
        this.copyFireInfo.cremation.ruleRemark = data.ruleRemark;
        this.$forceUpdate()

        //数据读取成功
      }).catch(error => {
        this.$message(error)
      })
    },
    //保存
    Save() {
      if ((Date.now() - this.onpresscTime) > 2000) {
        this.onpresscTime = Date.now()
        console.log(Date.now())
      } else {
        return
      }
      let this_save = this;
      let furnaceTypeCode = typeof this.copyFireInfo.cremation.furnaceTypeCode == 'number' && this.copyFireInfo.cremation.furnaceTypeCode >= 0

      if (!this.copyFireInfo.cremation.furnaceTypeCode || (!this.copyFireInfo.cremation.appointmentDate && !this.selectShow.showtime)) {
        this.$message("信息未填写完整")
        return;
      }
      //console.log(this.selectShow.showtime);
      if (this.copyFireInfo.cremation.asAppointment==1) {
        //判断并赋值
        this.copyFireInfo.cremation.appointmentDate = (this.selectShow.showtime) ? this.selectShow.showtime.substring(0, 10) : dataFormate(new Date(this.copyFireInfo.cremation.appointmentDate));
      }else
      {
        this.copyFireInfo.cremation.appointmentDate = dataFormate(new Date(this.copyFireInfo.cremation.appointmentDate));
      }

      //预约时间段范围
      this.copyFireInfo.cremation.appointmentTimeSegment = (this.selectShow.showtime) ? this.selectShow.showtime.substring(11, 23) : "";
      let obj = JSON.parse(JSON.stringify(this.copyFireInfo.cremation))
      obj.charges.goodsServices.forEach((item, index) => {
        if (item.asSettled == 1) {
          obj.charges.goodsServices.splice(index, 1)
        }
      })

      //新增标识
      if (this.FireAddFlag) {
        obj.id = 0
        obj.furnaceTypeCode = obj.furnaceTypeCode
        obj.asAppointment = obj.asAppointment
        obj.realityStartTime = ""
        obj.realityCoolingTime = ""
        obj.realityFinishTime = ""
        obj.cremationNo = ""
        obj.asTakeAsh = 0
        obj.randomCode = ""
        obj.version = 0
        obj.charges.businessCharge.id = 0
        obj.charges.businessCharge.businessCode = obj.businessCode
        obj.charges.businessCharge.discountCharge = 0
        obj.charges.businessCharge.benefitCharge = 0
        obj.charges.businessCharge.asSettled = 0
        obj.charges.businessCharge.chargeSettleId = 0
        obj.charges.businessCharge.randomCode = 0
        obj.charges.businessCharge.version = 0
        obj.charges.businessCharge.chargeTime = ""
        obj.charges.businessCharge.itemCharge = toFixed(this.FireInfo.cremation.charges.businessCharge.itemCharge, 2)
        obj.charges.businessCharge.realityCharge = toFixed(this.FireInfo.cremation.charges.businessCharge.itemCharge, 2)
      }
      //更新业务编码
      if (obj.charges.goodsServices.length > 0) {
        obj.charges.goodsServices.forEach((item, index) => {
          //更新业务编码
          item.businessCode = obj.businessCode
          item.discountCharge = toFixed(item.discountCharge, 2)
          item.itemCharge = toFixed(item.itemCharge, 2)
          item.itemPrice = toFixed(item.itemPrice, 2)
          item.itemNumber = toFixed(item.itemNumber, 2)
        })
      }
      let postData = obj
      this.saveFlag = true;
      Type['savecremation'](postData).then(response => {
        let result = response;
        const {data} = result
        if (!data) {
          this.saveFlag = false;
          this.$message('数据保存失败')
          return
        }
        //数据读取成功
        this.copyFireInfo.cremation = data
        this.saveFlag = false;
        this.$message('保存数据成功')
        this.$parent.DialogFire = false
      }).catch(error => {
        this.$message(error)
        this.saveFlag = false;
      })
    },
    //追加
    AddRow(index) {
      let row = this.copyGoodServices[index]
      if (index >= 0 && row) {
        row.itemPrice = Number(row.itemPrice).toFixed(2);
        row.itemNumber = Number(row.itemNumber).toFixed(2);
        row.itemCharge = Number((row.itemPrice * row.itemNumber)).toFixed(2);   //计算项目金额
        row.discountCharge = Number(row.discountCharge).toFixed(2);
        let numberValidate = Number(row.itemPrice) >= 0 && Number(row.itemNumber) >= 0 && Number(row.discountCharge) >= 0
        if (!numberValidate || !Number(row.itemCharge) || (Number(row.itemCharge) < Number(row.discountCharge))) {
          this.$message("数值错误，请重新填写")
          Object.assign(row, this.copyFireInfo.serviceItems.use_in_cremation[index])
          return true
        }
        // 减免金额
        row.benefitCharge = 0;
        row.asSettled = 0;
        //子项目的serviceItemId=id;
        row.serviceItemId = row.id;
        //新增的id为0
        row.id = 0;

        let list = JSON.parse(JSON.stringify(this.copyGoodServices));
        this.copyFireInfo.cremation.charges.goodsServices.push(list[index])
        Object.assign(row, this.copyFireInfo.serviceItems.use_in_cremation[index])
      }
    },
    //删除火化任务明细
    deleteRow(index, arry) {
      let this_delete = this;
      //定义要删除的数据
      let item = {
        "id": arry[index].id,
        "version": arry[index].version
      };
      //先添加删除，后再删除服务物品
      let deleteItems = this_delete.copyFireInfo.cremation.charges.deleteIds || [];
      if (arry[index] && item.id != 0) {
        //放入删除数据中
        deleteItems.push(item);
        //放入要要删除的数组中
        this_delete.copyFireInfo.cremation.charges.deleteIds = deleteItems;
      }

      //删除指定数据
      this_delete.copyFireInfo.cremation.charges.goodsServices.splice(index, 1);
    },
    closeDialog() {
      this.$parent.DialogFire = false
    },
    //全替换字符串
    replaceAll(str, s1, s2) {
      return str.replace(new RegExp(s1, "gm"), s2);
    },
    //通过选择对话框,加载时间段
    select(time) {
      if (!time) {
        return
      }
      let this_time = this;
      let furnaceTypeCode = this_time.copyFireInfo.cremation.furnaceTypeCode;
      let appointmentDate = this_time.copyFireInfo.cremation.appointmentDate;
      //通过自定义方法，替换所有字符串
      // time = this_time.replaceAll(time, '/', '-');

      let postData = {
        "furnaceTypeCode": furnaceTypeCode,
        "appointmentDate": dataFormatetmd(time)
      }
      Type['loadAppointmentTimeSegmentWithDate'](postData).then(response => {
        let result = response;
        const {data} = result
        if (!data) {
          this.$message('数据加载失败')
          return
        }
        //数据读取成功
        this.timeList = data
      }).catch(error => {
        this.$message(error)
      })
    },
    //根据类型和火化时间弹出火化时间段
    timeSelect(index) {
      if (this.timeList[index].state == 1) {
        this.$message("已被占用,请选择其他")
        return
      }
      for (let j = 0; j < this.timeList.length; j++) {
        this.timeList[j].flag = false
      }
      this.timeList[index].flag = !this.timeList[index].flag
      this.selectClick = this.timeList[index]
    },
    //显示选中的时间段
    showSelectName() {
      if (this.searchDate && this.selectClick.appointmentTimeSegment) {
        this.selectShow = this.selectClick
        this.selectShow.showtime = dataFormatetmd(new Date(this.searchDate)) + " " + this.selectClick.appointmentTimeSegment
        this.selectShow.date = this.searchDate
        this.centerDialogVisible = false
      } else {
        this.$message("请选择时间段")
      }
    },
    showDialog() {
      if (!this.copyFireInfo.cremation.furnaceTypeCode) {
        this.$message("请选择火化类型")
        return
      }
      if (this.copyFireInfo.cremation.charges.businessCharge.asSettled==1){
        this.$message("已结算,不能修改")
        return
      }
      this.timeList = []
      // this.selectShow = {},
      this.searchDate = ""
      this.selectClick = {}
      this.centerDialogVisible = true
    }, // 检查逝者选择是否遗体val选择遗体类型
    checkDeadUser(val) {
      let this_check = this;
      let code = this_check.copyFireInfo.cremation.businessCode;
      if (!code) {
        this_check.$message("请输入业务编码");
        return
      }
      let postData = {
        "businessCode": code
      }
      //查询逝者身份信息
      Type['loadservicenegotiationwithbusinesscode'](postData).then(response => {
        const {data} = response;
        if (!data) {
          this_check.$message('数据读取失败')
          return
        }
        //验证火化类型【遗体】是否满足
        if (val == this_check.cremationType && data.funeralDead.certificateNo != "" && (data.funeralDead.certificateNo == data.familyMember.certificateNo || data.funeralDead.certificateNo == data.familyAgent.certificateNo)) {
          this_check.$message("火化类型选择遗体条件不满足")
          //重置火化类型为空
          this_check.copyFireInfo.cremation.cremationChargeTypeCode = null;
          return
        }
        //数据读取成功
      }).catch(error => {
        this_check.$message(error)
      })
    },//通过code查询用途名称
    getPurposeByCode(code) {
      let purposeStr = "";
      if (this.cremationChargeTypes && this.cremationChargeTypes.length) {
        for (let i = 0; i < this.cremationChargeTypes.length; i++) {
          if (code == this.cremationChargeTypes[i].dataCode) {
            purposeStr = this.cremationChargeTypes[i].dataText;
            break;
          }
        }
      }
      return purposeStr;

    }
  }
}
</script>

<style>
.FireDialog .el-dialog__title, .FireDialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.FireDialog .el-input, .FireDialog .el-select, .FireDialog .el-form-item__content {
  width: 242px;
}

.FireDialog .selecttime .el-input {
  width: 150px;
}

.FireDialog .el-input--suffix .el-input__inner {
  padding-right: 0px;
}

.FireDialog .date input {
  width: 80px;
}

.FireDialog .calendar-day {
  text-align: center;
  color: #202535;
  line-height: 40px;
  font-size: 12px;
}

.FireDialog .el-calendar-table .el-calendar-day {
  height: 40px;
  text-align: center;
}

.FireDialog .is-selected {
  color: #F8A535;
  font-size: 10px;
  margin-top: 5px;
}
</style>
<style scoped>
.wrapper {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  margin: 5px 0px;
  align-content: flex-start;
  justify-content: space-between;
  float: right;
  padding: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.box-card {
  flex: 0 0 120px;
  display: inline-block;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);;
  margin-bottom: 30px;
  margin-right: 10px;
  height: 30px;

}

.box-card .item {
  font-size: 16px;
  font-weight: 400;
  line-height: 30px;
  width: 100%;
  height: 30px;
  text-align: left;
  padding: 0 1em;
  border-radius: 5px;
  overflow: hidden;
}

.item:hover {
  cursor: pointer;
}

.item:last-child {
  margin-bottom: 0px;
}

.item.employ {
  background-color: #FF6040;
}

.item.free {
  background: white;
}

.item.selected {
  background: lightgreen;
}
</style>

